<!-- 总览 -->
<template>
  <div v-loading="loading" class="energy_consume">
    <px-row :gutter="16">
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'费用总览'" />
          <div class="overview-wrap">
            <div class="lf">
              能耗费用合计:<span class="text">{{ totalCost }}</span> 万元
            </div>
            <div class="rt">
              同比<span class="yoy">{{ yoyVal || "-" }}</span>
            </div>
          </div>
          <px-table class="table-wrap" max-height="240px" :data="tableData" size="small" border stripe>
            <px-table-column prop="sort" label="排行" width="40" show-overflow-tooltip fixed="left" />
            <px-table-column prop="type" label="能源类型" min-width="23" show-overflow-tooltip />
            <px-table-column prop="cost" label="费用（万元）" min-width="35" show-overflow-tooltip />
            <px-table-column prop="mom" label="环比" min-width="25" show-overflow-tooltip />
            <px-table-column prop="yoy" label="同比" min-width="25" show-overflow-tooltip />
            <px-table-column prop="ratio" label="占比" min-width="25" show-overflow-tooltip />
          </px-table>
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'费用占比'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'ratioChartRef')"
          />
          <px-empty v-if="resData?.costRatio === null || resData?.costRatio?.length === 0" />
          <div v-else ref="ratioChartRef" class="chart-wrap" />
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'费用趋势'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'trendChartRef')"
          />
          <px-empty v-if="resData?.costTrend === null || resData?.costTrend?.xaxis.length === 0" />
          <div v-else ref="trendChartRef" class="chart-wrap" />
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'电'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'electricChartRef')"
          />
          <px-empty v-if="resData?.costElectricity === null || resData?.costElectricity?.xaxis.length === 0" />
          <div v-else ref="electricChartRef" class="chart-wrap" />
        </div>
      </px-col>
    </px-row>
    <px-row :gutter="16" class="mg-top-16">
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'水'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'waterChartRef')"
          />
          <px-empty v-if="resData?.costWater === null || resData?.costWater?.xaxis.length === 0" />
          <div v-else ref="waterChartRef" class="chart-wrap" />
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'大宗气'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'gasChartRef')"
          />
          <px-empty v-if="resData?.costGas === null || resData?.costGas?.xaxis.length === 0" />
          <div v-else ref="gasChartRef" class="chart-wrap" />
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'天然气'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'ngChartRef')"
          />
          <px-empty v-if="resData?.costNg === null || resData?.costNg?.xaxis.length === 0" />
          <div v-else ref="ngChartRef" class="chart-wrap" />
        </div>
      </px-col>
      <px-col :span="6">
        <div class="black">
          <modelTitle :title="'蒸汽/热水'" />
          <btnImageAndData
            v-has="'ALL_ENERGY_COST_SUPPLY_DOWNLOAD'"
            class="btn"
            :exportData="Boolean(false)"
            @exportChange="val => handlerExport(val, 'streamChartRef')"
          />
          <px-empty v-if="resData?.costHotSteam === null || resData?.costHotSteam?.xaxis.length === 0" />
          <div v-else ref="streamChartRef" class="chart-wrap" />
        </div>
      </px-col>
    </px-row>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from "vue";
import { getOverViewDataAPI } from "@/api/energy/supplyCost";
import { drawLineChart, drawPieChart, drawBarChart, drawStackingBarChart } from "@/views/common/energy/cost/supplyCost/utils";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import btnImageAndData from "@/views/common/energy/components/btnImageAndData/index.vue";

const { proxy } = getCurrentInstance();

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({
      timeType: "Monthly",
      factory: "",
      timeRange: []
    }),
    required: true
  }
});

const trendChartRef = ref();
const ratioChartRef = ref();
const electricChartRef = ref();
const waterChartRef = ref();
const gasChartRef = ref();
const ngChartRef = ref();
const streamChartRef = ref();

const state = reactive({
  loading: false,
  totalCost: 0,
  tableData: [],
  yoyVal: "",
  resData: {}
});
const { loading, totalCost, tableData, yoyVal, resData } = toRefs(state);

let chartObj = {};
// 查询
const getData = async () => {
  try {
    state.loading = true;
    const p = props.queryParams;
    const params = {
      dimension: p.timeType === "Monthly" ? "M" : "Y",
      startDate: p.timeRange.length > 0 ? p.timeRange[0] : "",
      endDate: p.timeRange.length > 0 ? p.timeRange[1] : "",
      level: p.factory
    };
    const res = await getOverViewDataAPI(params);
    let costSummaryTable = res.costSummaryTable?.length ? res.costSummaryTable : [];
    costSummaryTable.forEach(item => {
      item.mom = item.mom ? item.mom + "%" : "-";
      item.yoy = item.yoy ? item.yoy + "%" : "-";
      item.ratio = item.ratio ? item.ratio + "%" : "";
    });
    state.resData = res;
    state.totalCost = res.summary;
    state.yoyVal = res.summaryYoy;
    state.tableData = costSummaryTable;
    nextTick(() => {
      if (res.costTrend.xaxis.length) {
        chartObj.trendChartRef = drawStackingBarChart(trendChartRef.value, res.costTrend.xaxis, res.costTrend.yaxis);
      }
      if (res.costRatio) {
        chartObj.ratioChartRef = drawPieChart(ratioChartRef.value, res.costRatio);
      }
      if (res.costElectricity.xaxis.length) {
        chartObj.electricChartRef = drawBarChart(electricChartRef.value, res.costElectricity.xaxis, res.costElectricity.yaxis[0].value, 9);
      }
      if (res.costWater.xaxis.length) {
        chartObj.waterChartRef = drawBarChart(waterChartRef.value, res.costWater.xaxis, res.costWater.yaxis[0].value, 10);
      }
      if (res.costGas.xaxis.length) {
        chartObj.gasChartRef = drawBarChart(gasChartRef.value, res.costGas.xaxis, res.costGas.yaxis[0].value, 12);
      }
      if (res.costNg.xaxis.length) {
        chartObj.ngChartRef = drawBarChart(ngChartRef.value, res.costNg.xaxis, res.costNg.yaxis[0].value, 11);
      }
      if (res.costHotSteam.xaxis.length) {
        chartObj.streamChartRef = drawStackingBarChart(streamChartRef.value, res.costHotSteam.xaxis, res.costHotSteam.yaxis);
        let seriesData = [];
        res.costHotSteam.yaxis?.forEach((item, index) => {
          seriesData.push({
            stack: "Total",
            name: item.name,
            type: "bar",
            data: item.value,
            color: index === 0 ? "#40D3FF" : "#8573E2"
          });
        });
        chartObj.streamChartRef.setOption({
          series: seriesData
        });
      }
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const getParams = () => {
  const p = props.queryParams;
  const dimensionMap = {
    Hourly: "H",
    Daily: "D",
    Monthly: "M",
    Yearly: "Y"
  };
  let dimension = dimensionMap[p.timeType];
  let startDate = p.timeRange.length > 0 ? p.timeRange[0] : "";
  let endDate = p.timeRange.length > 0 ? p.timeRange[1] : "";
  return {
    dimension,
    startDate,
    endDate
  };
};
// 导出
const handleExport = () => {
  const { dimension, startDate, endDate } = getParams();
  const params = {
    dimension: dimension,
    startDate: startDate,
    endDate: endDate
  };
  proxy.download("post", "/energy/energyCost/exportSupplySummary", params, "供给费用-总览.xlsx");
};

defineExpose({
  getData,
  handleExport
});

// 导出方法
const handlerExport = (val1, val2) => {
  let myChart = chartObj[val2];
  if (!myChart) return;
  if (val2 === "trendChartRef") {
    myChart.setOption({
      legend: {
        type: "plain" // 改为普通模式显示全部图例
      }
    });
  }
  // 获取Base64图片数据
  const imgUrl = myChart.getDataURL({
    type: "png",
    pixelRatio: 2,
    backgroundColor: "#fff"
  });
  if (val2 === "trendChartRef") {
    myChart.setOption({
      legend: {
        show: true,
        type: "scroll",
        right: 20
      }
    });
  }

  // 创建并触发下载链接
  const link = document.createElement("a");
  link.href = imgUrl;
  link.download = "chart.png";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
</script>

<style lang="scss" scoped>
@import url("@/views/common/energy/cost/supplyCost/scss/common.scss");

.overview-wrap {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-top: 10px;

  .lf {
    .text {
      margin-left: 6px;
      font-size: 20px;
      font-weight: 500;
      color: rgb(0 0 0 / 80%);
    }
  }

  .rt {
    .yoy {
      margin-left: 6px;
    }
  }
}

.table-wrap {
  flex: 1;
  margin-top: 8px;
}
</style>
